package com.liu.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.liu.constant.Constants;
import com.liu.core.RedisTemplate;
import com.liu.entity.LiuLoginUser;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Set;

/**
 * @ClassName BaseController
 * @Author liuxin
 * @Date Created in 2023-01-29 14:30
 * @Version 1.0
 */

public class BaseController {

    @Resource
    RedisTemplate redisTemplate;

    /**
     * 作用是通过redis获取当前登录用户信息
     * @return
     */
    protected LiuLoginUser getLoginUser(){
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = request.getHeader(Constants.TOKEN_AUTHORIZATION);
        if (token == null) {
            throw new RuntimeException("这里是server的登录出现了异常，获取token失败");
        }
        Set<String> keys = redisTemplate.keys(Constants.TOKEN_PREFIX + "*" + token);
        if (keys == null || keys.size() == 0) {
            throw new RuntimeException("这里是server的登录出现了异常，获取key失败");
        }
        String tokenKey = (String) keys.toArray()[0];

        //3.使用token取redis中查看，有没有对应的loginUser
        return redisTemplate.getObject(tokenKey, new TypeReference<LiuLoginUser>() {

        });
    }
}
